package cn.tedu.sp02.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {


    @Autowired
    private ItemService itemService;

    @GetMapping("/{orderId}")   //restful形式要添加注解   普通形式不用
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        List<Item> items = itemService.getItems(orderId);
        //有90%的概率进入该延迟代码 延迟时间是隋剑的0-5秒
        if(Math.random() < 0.9){
            int t = new Random().nextInt(5000);
            System.out.println("延迟："+t);
            Thread.sleep(t);
        }
        return JsonResult.build().code(200).data(items);
    }


    @PostMapping("/decreaseNumber")  //前端传过来是对象中间会转化为json，需要用注解转化为对象
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        itemService.decreaseNumber(items);
        return JsonResult.build().code(200).msg("减少库存成功");
    }

    @GetMapping("/favicon.ico")
    public void ico(){

    }
}
